
import { InjectRepository } from '@nestjs/typeorm';
import { Repository ,Not ,In,Like} from 'typeorm';
import { Injectable } from '@nestjs/common';
import { ResultData } from 'src/common/utils/result';
import {ProfessionalSchoolEntity} from "./entities/professional-school.entity";
import {CreateSchoolDto, QuerySchoolDto, UpdateSchoolDto} from "./dto/professional-school.dto";

@Injectable()
export class ProfessionalSchoolService {
constructor(
    @InjectRepository(ProfessionalSchoolEntity)
    private readonly professionalSchoolEntityRep: Repository<ProfessionalSchoolEntity>,
) {}
    async createSchool(createSchoolDto: CreateSchoolDto) {
        const entity = this.professionalSchoolEntityRep.createQueryBuilder('entity');
        entity.where({ delFlag: '0'});
        // 查找是否已存在 学校ID和专业ID相同的记录，如果存在则不允许添加，返回错误信息
        const existingRecord = await entity.where({ proId: createSchoolDto.proId, schoolId: createSchoolDto.schoolId }).getOne();
        if (existingRecord) {
            return ResultData.fail(500, '该学校已开设改专业，请勿重复添加！');
        }
        const res = await this.professionalSchoolEntityRep.save(createSchoolDto);
        return ResultData.ok(res);
    }

    // 数据处理函数
    private  returnFormatDate(data) {
        return data.map(item=>({
            ...item,
            schoolName: item.school?.schoolName,
            proName: item.professional?.proName,
        }))
    }

    async findAllSchool(query :QuerySchoolDto ) {
        const entity = this.professionalSchoolEntityRep.createQueryBuilder('entity');
        // 关联查询
        entity.leftJoinAndSelect('entity.school', 'school');
        entity.leftJoinAndSelect('entity.professional', 'professional');
        entity.where({ delFlag: '0'});

        if(query.proId){
            entity.andWhere("entity.proId = :proId", {proId: query.proId});
        }
        if(query.schoolId){
            entity.andWhere("entity.schoolId = :schoolId", {schoolId: query.schoolId});
        }
        if(query.status){
            entity.andWhere("entity.status = :status", {status: query.status});
        }
        if(query.createBy){
            entity.andWhere("entity.createBy = :createBy", {createBy: query.createBy});
        }
        if(query.params?.beginTime && query.params?.endTime){
            entity.andWhere("entity.startDate BETWEEN :start AND :end", { start: query.params.beginTime, end: query.params.endTime });
        }
        if(query.remark){
            entity.andWhere("entity.remark = :remark", {remark: query.remark});
        }
        if (query.orderByColumn && query.isAsc) {
            const key = query.isAsc === 'ascending' ? 'ASC' : 'DESC';
            entity.orderBy(`entity.${query.orderByColumn}`, key);
        }

        // 如果没有分页参数则返回所有数据
        if (!query.pageSize || !query.pageNum) {
            const list = await entity.getMany()
            return ResultData.ok(this.returnFormatDate(list));
        }

        entity.skip(query.pageSize * (query.pageNum - 1)).take(query.pageSize);
        const [list, total] = await entity.getManyAndCount();

        return ResultData.ok({
            list:this.returnFormatDate(list),
            total,
        });
    }

    async updateSchool(updateSchoolDto:UpdateSchoolDto){
        const entity = this.professionalSchoolEntityRep.createQueryBuilder('entity');
        entity.where({ delFlag: '0'});
        // 查找是否已存在 学校ID和专业ID相同的记录(排除自己的记录)，如果存在则不允许添加，返回错误信息
        const existingRecord = await entity.where({ proId: updateSchoolDto.proId, schoolId: updateSchoolDto.schoolId, id: Not(updateSchoolDto.id) }).getOne();
        if (existingRecord) {
            return ResultData.fail(500, '该学校已开设改专业，请勿重复添加！');
        }
        const res = await this.professionalSchoolEntityRep.update({  id: updateSchoolDto.id }, updateSchoolDto);
        return ResultData.ok({value:res.affected >= 1});
    }

    async findOneSchool(id:number){
        const res = await this.professionalSchoolEntityRep.findOne({
            where: {
                delFlag: '0',
                id: id,
            },
        });
        return ResultData.ok(res);
    }

    async removeSchool(ids:number[]){
        const res = await this.professionalSchoolEntityRep.update(
            { id: In(ids) },
            {
                delFlag: '1',
            },
        );
        return ResultData.ok({value:res.affected >= 1});
    }

}
